package com.hna.eking.Controller;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

public class RunSqlContent {
	private static final Logger logger = LoggerFactory.getLogger(RunSqlContent.class);
	
	@RequestMapping(value = "/RunSqlContext.do", method = RequestMethod.GET)
	public String FileCtlGet(@RequestParam(value = "Parm") String Parm) {

		logger.debug("parm = " + Parm);
		JSONObject json = JSONObject.parseObject(Parm);
		logger.debug("parm = " + json.toJSONString());
		/* get table name from request */
		String TableName = json.getString("TableName");
		logger.debug("TableName:" + TableName);
		/* get return list include predicate from request */
		JSONArray RetArry = json.getJSONArray("RetList");
		String RetList = " ";// first space here
		for (int i = 0; i < RetArry.size(); i++) {
			JSONObject RetItem = RetArry.getJSONObject(i);
			String RetStr = String.format("%s(%s)", RetItem.getString("Predicate"), RetItem.getString("RetItem"));
			logger.debug("Ret List:" + RetStr);

			if (RetArry.size() == i + 1) {
				RetList = RetList + RetStr + " ";
				continue;
			}
			RetList = RetList + RetStr + ",";
		}

		/* get group list from request */
		JSONArray GrpArry = json.getJSONArray("GrpList");
		String grpList = " ";// first space here
		for (int i = 0; i < GrpArry.size(); i++) {
			JSONObject GrpItem = GrpArry.getJSONObject(i);
			String GrpStr = GrpItem.getString("GrpName");
			logger.debug("Group List:" + GrpStr);

			if (GrpArry.size() == i + 1) {
				grpList = grpList + GrpStr + " ";
				continue;
			}
			grpList = grpList + GrpStr + ",";
		}

		/* joint sql string from request string */
		String SqlStr = String.format("select %s from %s where 1 = 1 group by %s", RetList, TableName, grpList);
		logger.debug("sql string is:" + SqlStr);
		/* get result from file with spark sql */

		/* joint result json */
		JSONObject resultObj = new JSONObject();
//		SparkRunHive hivectx = new SparkRunHive();
//		hivectx.RunSql(SqlStr);
		return SqlStr;

	}

}
